<?php

namespace App\Services;

use App\Models\Classify;
use App\Models\PartCompany;
use App\Models\ProjectClassify;
use App\Models\UserLoginInfo;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class HomeService extends BaseService
{
    /**
     * 获取登陆地数据
     *
     * @return array
     * @author: lxk
     * @date: 2024/6/14 15:42
     */
    public function getLngAndLat(): array
    {
        $list  = UserLoginInfo::query()->pluck('login_address')->toArray();
        $addressCount = array_count_values($list);
        $list2 = UserLoginInfo::query()
            ->distinct()
            ->select('login_address', 'login_lng', 'login_lat')
            ->get()
            ->toArray();
        $result = [];
        foreach ($list2 as $key2=>$val2) {
            $loginCount = $addressCount[$val2['login_address']];
            if ($loginCount < 10) {
                $loginCount = 10;
            } elseif ($loginCount < 20) {
                $loginCount = 20;
            } elseif ($loginCount > 200) {
                $loginCount = 200;
            }
            $result[$key2]['value'] = [$val2['login_lng'], $val2['login_lat'], $loginCount];
        }
        return $result;
    }

    /**
     * 获取单位工程的案卷
     *
     * @param $partCompanyIds
     * @return array[]
     * @author: lxk
     * @date: 2024-10-18 13:37
     */
    public static function getProClassBtCounts($partCompanyIds) : array
    {
        $list = ProjectClassify::query()
            ->whereIn('part_company_id', $partCompanyIds)
            ->select('id', 'part_company_id', 'major_code')
            ->get()
            ->toArray();
        $newList = [];
        foreach ($list as $val) {
            $table = "book_titles_{$val['part_company_id']}_{$val['id']}";
            if (Schema::hasTable($table)) {
                $count = DB::table($table)->whereNull('deleted_at')->count(); //单位工程案卷总数
                $newList[$val['major_code']][] = $count;
            }
        }
        $result = [];
        foreach ($newList as $key2=>$val2) {
            $result[$key2]['name']  = Classify::ZY[$key2] . '[' . $key2 . ']';
            $result[$key2]['value'] = array_sum($val2);
        }

        return array_values($result);
    }

    /**
     * 获取项目五个阶段的案卷数据
     *
     * @param $projectId
     * @return array
     * @author: lxk
     * @date: 2024-10-26 11:54
     */
    public static function getFiveStageTables($projectId) : array
    {
        $btCountResult   = [ //定义一个基础数组，保证每个阶段都有数据，哪怕为0
            1 => [], //预可行性研究阶段
            2 => [], //可行性研究阶段
            3 => [], //初步设计
            4 => [], //施工图设计
            5 => [], //施工竣工阶段
        ];
        $projectClassifyList = ProjectClassify::query()->select('id', 'stage_code')->get()->toArray();
        $projectClassifyIdStage = [];
        foreach ($projectClassifyList as $value) {
            $projectClassifyIdStage[$value['id']] = $value['stage_code'];
        }
        $partCompanyIds  = PartCompany::query()->where('project_id', $projectId)->pluck('id')->toArray();
        $bookTitleTables = CommonService::getSubTables('book_titles'); //获取全部book_titles分表
        foreach ($bookTitleTables as $table) {
            $btTotalCount = 0;
            $idInfo = CommonService::getTableParams($table);
            if (in_array($idInfo['id1'], $partCompanyIds) && isset($projectClassifyIdStage[$idInfo['id2']])) { //把分表中属于该项目的取出来
                $table = "book_titles_{$idInfo['id1']}_{$idInfo['id2']}";
                $stage = $projectClassifyIdStage[$idInfo['id2']];
                $count = DB::table($table)->whereNull('deleted_at')->count('id');
                $btTotalCount += $count;
                $btCountResult[$stage][] = $btTotalCount;
            }
        }
        $arr = [];
        ksort($btCountResult);
        foreach ($btCountResult as $val) {
            $arr[] = array_sum($val);
        }
        $fiveStage = [
            ['name' => '预可行性研究', 'value' => 0],
            ['name' => '可行性研究', 'value' => 0],
            ['name' => '初步设计', 'value' => 0],
            ['name' => '施工设计', 'value' => 0],
            ['name' => '施工竣工', 'value' => 0],
        ];
        $totalBtCount = array_sum($arr);
        foreach ($fiveStage as $key => &$val) {
            $percent      = $totalBtCount ? round($arr[$key] / $totalBtCount, 3) * 100 : 0;
            $percent      = $percent < 0.1 ? '（<0.1%）' : '（' . $percent . '%）';
            $val['name']  = $val['name'] . $percent;
            $val['value'] = $arr[$key];
        }

        return $fiveStage;
    }

    /**
     * 获取项目五个阶段的蓝图数据
     *
     * @param $projectId
     * @return array
     * @throws \App\Exceptions\ApiException
     * @throws \Doctrine\DBAL\Exception
     * @author: lxk
     * @date: 2024-10-26 11:54
     */
    public static function getBluePrintData($projectId) : array
    {
        $btCountResult = [ //定义一个基础数组，保证每个阶段都有数据，哪怕为0
            1 => [], //预可行性研究阶段
            2 => [], //可行性研究阶段
            3 => [], //初步设计
            4 => [], //施工图设计
            5 => [], //施工竣工阶段
        ];
        $btCountResult2 = [ //定义一个基础数组，保证每个阶段都有数据，哪怕为0
            1 => [], //预可行性研究阶段
            2 => [], //可行性研究阶段
            3 => [], //初步设计
            4 => [], //施工图设计
            5 => [], //施工竣工阶段
        ];
        $projectClassifyList = ProjectClassify::query()->select('id', 'stage_code')->get()->toArray();
        $projectClassifyIdStage = [];
        foreach ($projectClassifyList as $value) {
            $projectClassifyIdStage[$value['id']] = $value['stage_code'];
        }
        $partCompanyIds   = PartCompany::query()->where('project_id', $projectId)->pluck('id')->toArray();
        $bookTitleTables  = CommonService::getSubTables('book_titles'); //获取全部book_titles分表
        //$blueCatalogCount = 0; //蓝图卷内数
        foreach ($bookTitleTables as $table) {
            $blueBtCount    = 0; //蓝图案卷数
            $blueprintCount = 0; //蓝图张数
            $idInfo         = CommonService::getTableParams($table);
            if (in_array($idInfo['id1'], $partCompanyIds) && isset($projectClassifyIdStage[$idInfo['id2']])) { //把分表中属于该项目的取出来
                $bookTitleTable  = "book_titles_{$idInfo['id1']}_{$idInfo['id2']}";
                //$catalogTable    = "book_catalogs_{$idInfo['id1']}_{$idInfo['id2']}";
                $stage           = $projectClassifyIdStage[$idInfo['id2']];

                $btCountArr      = DB::table($bookTitleTable)->whereNull('deleted_at')->where('blueprint', '>', 0)->pluck('id')->toArray();
                $blueBtCount     += count($btCountArr); //蓝图案卷ids的数量
                $btCountResult[$stage][] = $blueBtCount;

                //$catalogCount     = DB::table($catalogTable)->whereNull('deleted_at')->whereIn('book_title_id', $btCountArr)->count('id');
                //$blueCatalogCount += $catalogCount;

                $sumBlueprint   = DB::table($table)->whereNull('deleted_at')->sum('blueprint');
                $blueprintCount += $sumBlueprint;
                $btCountResult2[$stage][] = $blueprintCount;
            }
        }
        $btCount = $blueprintCount = [];
        ksort($btCountResult);
        foreach ($btCountResult as $val1) {
            $btCount[] = array_sum($val1);
        }
        ksort($btCountResult2);
        foreach ($btCountResult2 as $val2) {
            $blueprintCount[] = array_sum($val2);
        }
        redis()->set('blue_bt_count:' . $projectId, $btCount[1] + $btCount[2] + $btCount[3] + $btCount[4]); //总蓝图案卷
        //redis()->set('blue_ca_count:' . $projectId, $blueCatalogCount); //总蓝卷内数
        redis()->set('blue_pn_count:' . $projectId, $blueprintCount[1] + $blueprintCount[2] + $blueprintCount[3] + $blueprintCount[4]); //蓝图总张数
        return [
            [
                'name' => "可行性研究（{$btCount[1]} 卷, {$blueprintCount[1]} 张）",
                'value'=> $btCount[1],
            ],
            [
                'name' => "初步设计（{$btCount[2]} 卷, {$blueprintCount[2]} 张）",
                'value'=> $btCount[2],
            ],
            [
                'name' => "施工设计（{$btCount[3]} 卷, {$blueprintCount[3]} 张）",
                'value'=> $btCount[3],
            ],
            [
                'name' => "施工竣工（{$btCount[4]} 卷, {$blueprintCount[4]} 张）",
                'value'=> $btCount[4],
            ]
        ];
    }




}
